package org.example.serializer;

import org.example.RpcApp;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年12月26日 15:55
 */
public class SerializerFactory {
    private static final ConcurrentHashMap<String, Serializer> serializerMap = new ConcurrentHashMap<>();
    private static String serializerClassName = getSerializerClassName();
    public static String getSerializerClassName(){
        return RpcApp.getRpcConfig().getSerializer();
    }
    public static Serializer getSerializer(String serializerClassName){
        // 验证类路径
//        System.out.println("序列化"+getSerializerByName(serializerClassName));
        return getSerializerByName(serializerClassName);
    }

    public static Serializer getSerializer(){
        // 验证类路径
        return getSerializerByName(serializerClassName);
    }

    private static Serializer getSerializerByName(String serializerClassName) {
        if (serializerClassName == null || serializerClassName.trim().isEmpty()) {
            throw new IllegalArgumentException("Serializer class name cannot be null or empty.");
        }
        return serializerMap.computeIfAbsent(serializerClassName, className -> {
            try {
                // 动态加载类并创建实例
                Class<?> clazz = Class.forName(className);
                if (!Serializer.class.isAssignableFrom(clazz)) {
                    throw new IllegalArgumentException("Class " + className + " is not a valid Serializer.");
                }
                return (Serializer) clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Failed to create serializer instance for class: " + className, e);
            }
        });
    }
}
